﻿using System;
using System.Collections.Specialized;
using System.Web.Mvc;
using BSU.CSCE.Data.Model;
using BSU.CSCE.Services;
using BSU.CSCE.Utilities;

namespace BSU.CSCE.Web.Binders
{
    public class PublicationBinder : BaseModelBinder
    {
        #region IModelBinder Members

        public override object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Administrator administrator = new Administrator();

            Publication publication = bindingContext.Model as Publication ?? new Publication();
            NameValueCollection form = controllerContext.HttpContext.Request.Form;

            publication.Title = form[Reflector.GetPropertyName<Publication>(x => x.Title)].EmptyToNull();
            publication.ShortDescription = form[Reflector.GetPropertyName<Publication>(x => x.ShortDescription)].EmptyToNull();
            publication.Description = form[Reflector.GetPropertyName<Publication>(x => x.Description)].EmptyToNull();
            
            int typeId;
            if (Int32.TryParse(form[Reflector.GetPropertyName<Publication>(x => x.Type)], out typeId))
                publication.Type = (PublicationType)typeId;

            int statusId;
            if (Int32.TryParse(form[Reflector.GetPropertyName<Publication>(x => x.Status)], out statusId))
                publication.Status = (PublicationStatus)statusId;

            DateTime publishingTime;
            if (DateTime.TryParse(form[Reflector.GetPropertyName<Publication>(x => x.PublishingTime)], out publishingTime))
                publication.PublishingTime = publishingTime;

            return publication;
        }

        #endregion
    }
}
